/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
**     of its contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "highlighter.h"

Highlighter::Highlighter(QTextDocument *doc, QObject *parent)
    : document(doc), QObject(parent)
{
    highlightingRules.clear();
}

void Highlighter::ruleChange(QString text)
{
    HighlightingRule rule;
    highlightingRules.clear();

    rule.format.setForeground(Qt::darkRed);
    rule.pattern = text;
    highlightingRules.append(rule);

    highlightBlock();
}

bool Highlighter::findBlock(int pos, int length, HighlighterPrivate &blocks)
{
    QTextBlock blockTmp;
    int currenLen;

    currenLen = 0;
    blockTmp = document->begin();
    while (blockTmp.isValid() && currenLen <= pos)
    {
        /* 加上之后相等了，就说明start为下一个block的开始 */
        if (currenLen + blockTmp.length() == pos)
        {
            currenLen += blockTmp.length();
            blockTmp = blockTmp.next();
            break;
        }
        else if (currenLen + blockTmp.length() > pos)
        {
            break;
        }

        currenLen += blockTmp.length();

        blockTmp = blockTmp.next();
    }

    if (!blockTmp.isValid())
    {
        return false;
    }

    /* 开始的block */
    blocks.blocks.append(blockTmp);

    /* 开始位置 */
    if (currenLen + blockTmp.length() == pos)
    {
        blocks.start = 0;
    }
    else
    {
        blocks.start = pos - currenLen;
    }

    /* 统计block */
    if (pos + length > currenLen + blockTmp.length())
    {
        while (blockTmp.isValid()
               && (pos + length > currenLen + blockTmp.length()))
        {
            currenLen += blockTmp.length();
            blockTmp = blockTmp.next();

            blocks.blocks.append(blockTmp);
        }

        if (blockTmp.isValid())
        {
            blocks.end = pos + length - currenLen;
        }
        else
        {
            blocks.end = this->document->lastBlock().length();
        }
    }
    else
    {
        blocks.end = length;
    }

    return true;
}

void Highlighter::setBlockFormat1(HighlighterPrivate &blocks, QTextCharFormat format)
{

    QTextBlock textBlock;
    QTextLayout *layout = NULL;
    QTextLayout::FormatRange r;
    QList<QTextLayout::FormatRange> ranges;

    if (blocks.blocks.count() == 1)
    {
        textBlock = blocks.blocks.first();
        layout = textBlock.layout();

        r.start = blocks.start;
        r.length = blocks.end - blocks.start;
        r.format = format;

        ranges << r;

        qDebug() << "Range : start: "  << r.start << "  length:" << r.length;

        layout->setAdditionalFormats(ranges);
        this->document->markContentsDirty(textBlock.position(), textBlock.length());
        return;
    }

    foreach (textBlock, blocks.blocks)
    {
        layout = textBlock.layout();
        ranges.clear();
        if (textBlock == blocks.blocks.first())
        {
            r.start = blocks.start;
            r.length = textBlock.length() - blocks.start - 1;
            r.format = format;

            qDebug() << "1. Range : start: "  << r.start << "  length:" << r.length;
        }
        else if (textBlock == blocks.blocks.last())
        {
            r.start = 0;
            r.length = blocks.end;
            r.format = format;

            qDebug() << "2. Range : start: "  << r.start << "  length:" << r.length;
        }
        else
        {
            r.start = 0;
            r.length = textBlock.length() - 1;
            r.format = format;

            qDebug() << "3. Range : start: "  << r.start << "  length:" << r.length;
        }

        ranges << r;
        layout->setAdditionalFormats(ranges);
    }

    this->document->markContentsDirty(textBlock.position(), textBlock.length());
}

void Highlighter::highlightBlock()
{
    QString str1 = this->document->toPlainText();
    HighlighterPrivate blocks;

    if (str1.length() == 0)
    {
        return;
    }

#if 1
    pcre *pc;
    int rt, i;
    const char *err;
    int offset;
    int vector[2] = {0, 0};
    int cnt = 0;

    int nOptions = PCRE_EXTENDED | PCRE_UTF8;

    qDebug() << "Doc Len: " << str1.size();

    foreach (const HighlightingRule &rule, highlightingRules) {
        pc = pcre_compile(rule.pattern.toStdString().c_str(), nOptions, &err, &offset, NULL);
        if (pc == NULL){

            emit status(0, 0);
            qDebug() << "Compile reg fail;";
            return;
        }

        qDebug() << "Start mtach;";

        offset = 0;
        do{
            rt = pcre_exec(pc, NULL, str1.toStdString().c_str(), str1.size(), offset, 0, vector, 2);
            if (rt <= 0){
                emit status(1, 0);

                qDebug() << "Match fail;";
                return;
            }

            qDebug() << "Start Pos: " << vector[0] << " End Pos :" << vector[1];

            if (findBlock(vector[0], vector[1] - vector[0], blocks))
            {
                qDebug() << "Blocks: " << blocks.blocks.count() << " Start:" << blocks.start << " End:" << blocks.end;
                setBlockFormat1(blocks, rule.format);
            }

            cnt++;
            offset = vector[1];
        }while (rt > 0);

        pcre_free(pc);

        emit status(1, cnt);
    }
#else
    foreach (const HighlightingRule &rule, highlightingRules) {
        QRegExp reg (rule.pattern);
        int count = 0;
        int pos = 0;

        //reg.setMinimal(true);

        while ((pos = reg.indexIn(str1, pos)) != -1) {
            qDebug() << "Start Pos: " << pos << ", End Pos :" << reg.matchedLength();

            if (findBlock(pos, reg.matchedLength(), blocks))
            {
                qDebug() << "Blocks: " << blocks.blocks.count() << " Start:" << blocks.start << ", End:" << blocks.end;
                setBlockFormat1(blocks, rule.format);
            }

            ++count;
            pos += reg.matchedLength();
        }
    }

#endif
}
